package com.cras.webcam.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

import android.util.Log;

import com.cras.webcam.http.handler.AcceptHandler;

public class ServerBootstrap implements Runnable {
	private static final String LOG_TAG = ServerBootstrap.class.getName();
	private Selector selector;
	private static final int PORT = 9000;

	public ServerBootstrap(){
		try {
			// 打开监听信道
			ServerSocketChannel ssc = ServerSocketChannel.open();
			// 与本地端口绑定
			ssc.socket().bind(new InetSocketAddress(PORT));
			// 设置为非阻塞模式
			ssc.configureBlocking(false);
			// 创建选择器
			selector = Selector.open();
			// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作
			ssc.register(selector, SelectionKey.OP_ACCEPT,new AcceptHandler());
			Log.i(LOG_TAG,"server started...");
		} catch (IOException  e) {
			// TODO Auto-generated catch block
			Log.e(LOG_TAG,"http server init error",e);
		} catch(Exception e){
			Log.e(LOG_TAG,"http server init error",e);
		}
	}

	@Override
	public void run(){
				Log.i(LOG_TAG,"http server start......");
					while (true) {
						try {
							if (selector.selectNow() > 0) {
								Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
								while (keys.hasNext()) {
									SelectionKey key = keys.next();
									ChannelHandler channelHandler = (ChannelHandler) key.attachment();
									channelHandler.handle(key);
									keys.remove();
								}
							}
						} catch (Throwable e) {
							Log.e(LOG_TAG, "http server start error", e);
						}
					}

	}

	public void stop(){
		// TODO
		Log.i(LOG_TAG,"http server stop!");
	}
}
